import MSData
import MSLogger

import datetime
import time

def helper_insert_object(MSId, PCNId, MSObjects):
    found = False
    for obj in MSObjects:
        if MSId == obj.objectMSId:
            found = True
            obj.objectPCNId = PCNId
    if not found:
        obj = MSData.MSObject()
        obj.objectMSId = MSId
        obj.objectPCNId = PCNId
        MSObjects.append(obj)

def GET_MSObjects_FROM_CarOnline(dbCursor, MSObjects):
    query = 'SELECT id,uid FROM _devices'
    dbCursor.execute(query)
    uids  = dbCursor.fetchall()
    for uid in uids:
        try:
            query = 'SELECT login,password FROM _users WHERE defaultDevice=%s' % str(uid[0])
            dbCursor.execute(query)
            deviceData = dbCursor.fetchall()
            devicePCNId = deviceData[0][0].replace('dev','')
            helper_insert_object(int(uid[0]), int(devicePCNId), MSObjects)
        except Exception, err:
            #MSLogger.logError('GetObjects: error: %s' % (str(err)))
            continue

def GET_AllObjects_FROM_CarOnline(dbCursor, MSObjects):
    query = 'SELECT id,uid FROM _devices'
    dbCursor.execute(query)
    uids  = dbCursor.fetchall()
    for uid in uids:
        try:
            query = 'SELECT login,password FROM _users WHERE defaultDevice=%s' % str(uid[0])
            dbCursor.execute(query)
            deviceData = dbCursor.fetchall()
            devicePCNId = deviceData[0][0]
            helper_insert_object(int(uid[0]), devicePCNId, MSObjects)
        except Exception, err:
            MSLogger.logError('GetObjects: error: %s' % (str(err)))
            continue

def GET_LastRecId_FROM_sgn(dbCursor):
    query = "SELECT MAX(ID) FROM SGN"
    try:
        dbCursor.execute(query)
        buff    = dbCursor.fetchall()
        recId   = int(buff[0][0])
        return recId + 1
    except:
        return 1

def GET_LastRecId_FROM_records(dbCursor):
    query = "SELECT MAX(RID) FROM RECORDS"
    try:
        dbCursor.execute(query)
        buff    = dbCursor.fetchall()
        recId   = int(buff[0][0])
        return recId + 1
    except:
        return 1

def STORE_MSEvent_TO_obj(dbCursor, event):
    if not event.hasMobile:
        return
    recordSpeed     = event.GPSSpeed
    recordLat       = event.GPSLatitude
    recordLon       = event.GPSLongitude
    recordTime      = event.eventGenerateTime.strftime(MSData.TIME_FORMAT_PCN)
    recordObj       = event.objectId
    query = "UPDATE obj SET LAT='%s', LON='%s', SPD='%s', D_ONLINE='%s' WHERE ID='%s'" % (recordLat, recordLon, recordSpeed, recordTime, recordObj)
    try:
        dbCursor.execute(query)
        MSLogger.logDebug('query: %s' % (query))
    except:
        MSLogger.logError('failed to execute query: %s exception: %s' % (query, str(err)))

#TBD try w/out recId
def STORE_MSEvent_TO_sgn(dbCursor, event, recId):
    if not event.hasStatic:
        MSLogger.logDebug('StoreToSGN: event has not static data')
        return recId
    if event.contactIdType == None:
        MSLogger.logDebug('StoreToSGN: event has null contact id type')
        return recId
    if (datetime.datetime.fromtimestamp(time.time()) - event.eventGenerateTime) >= datetime.timedelta(0, 1800):
        MSLogger.logInfo('StoreToSGN: cant write message older than 30 mins: obj(%s) code (%s) generated(%s) received(%s)' % (str(event.objectId), str(event.contactIdType), str(event.eventGenerateTime.strftime(MSData.TIME_FORMAT_PCN)), str(event.eventReceiveTime.strftime(MSData.TIME_FORMAT_PCN))))
        return recId
                                
    recordId        = str(recId)
    recordIdMes     = str(event.contactIdType)
    recordIdObj     = str(event.objectId)
    recordSDate     = str(event.eventGenerateTime.strftime(MSData.TIME_FORMAT_PCN))
    recordXUser     = 'magicsys'
    recordPhone     = '434343'
    recordIDPr      = '2'
    recordIDPPL     = '-1'
    recordIDZon     = '-1'
    recordZona      = str(event.contactIdZona)
    recordRazdel    = str(event.contactIdGroup)
    recordSTR1      = str(event.contactIdFull)
    recordSTR2      = '5011 180994R65500000'
    recordCOMN      = 'GPRS'

    query = "INSERT INTO SGN (ID, ID_MES, ID_OBJ, SDATE, XUSER, PHONE, ID_PR, ID_PPL, ID_ZON, ZONA, RAZDEL, STR1, STR2, COMN) VALUES" + \
                             "('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % \
                             (recordId, recordIdMes, recordIdObj, recordSDate, recordXUser, recordPhone, recordIDPr, recordIDPPL, \
                              recordIDZon, recordZona, recordRazdel, recordSTR1, recordSTR2, recordCOMN)

    try:
        dbCursor.execute(query)
        MSLogger.logDebug('query: %s' % (query))
        recId += 1
    except (Exception), err:
        MSLogger.logDebug('query: %s' % (query))
        MSLogger.logError('failed to execute query: %s exception: %s' % (query, str(err)))
    return recId

def STORE_MSEvent_TO_records(dbCursor, event, recId):
    if not event.hasMobile:
        return recId
    recordSpeed = str(float(event.GPSSpeed)/1.85)
    recordLat = str(event.GPSLatitude)
    recordLon = str(event.GPSLongitude)
    recordTime = str(event.eventGenerateTime.strftime(MSData.TIME_FORMAT_PCN))
    recordObj = str(event.objectId)
    recordRID = str(recId)
    recordRecType = '2'
    recordPower = '2'
    recordCarPower = '1200'
    recordD1 = '2'
    recordD2 = '2'
    recordD3 = '2'
    recordD4 = '2'
    recordD5 = '2'
    recordD6 = '2'
    recordAN1 = '1200'
    recordAN2 = '1200'

    query = "INSERT INTO records (ID_OBJ, LAT, LON, SPD, REC_DATE, RID, REC_TYPE, POWER, CAR_POWER, AN1, AN2, D1, D2, D3, D4, D5, D6) VALUES" + \
            "('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % \
            (recordObj, recordLat, recordLon, recordSpeed, recordTime, recordRID, recordRecType, recordPower, recordCarPower, recordAN1, recordAN2, recordD1, recordD2, recordD3, recordD4, recordD5, recordD6)
    try:
        dbCursor.execute(query)
        MSLogger.logDebug('query: %s' % (str(query)))
        recId += 1
    except (Exception), err:
        MSLogger.logError('failed to execute query: %s exception: %s' % (query, str(err)))
    return recId

